package com.lifp.annotation.aspect;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Collection;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2023/9/5 22:09
 * @Version 1.0
 */
@Component
@Aspect
@Slf4j
public class BigDecimalPlainStringAspect {
    //切点，标注了自定义的注解@BigDecimalPlainString的类作为切点
    @Pointcut("@annotation(com.lifp.annotation.BigDecimalPlainString)")
    public void point(){}

    @Around("point()")
    public Object before(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = proceedingJoinPoint.proceed();

        handleBigDecimalValue(result);

        return result;
    }

    private void handleBigDecimalValue(Object result){
        if (result == null) {
            return;
        }

        if (result instanceof Collection) {
            //遍历对象
            for (Object o : ((Collection) result)) {
                handleValue(o);
            }
        } else {
            Class<?> clazz = result.getClass();
            if (clazz.isArray()) {
                Object[] array = (Object[]) result;
                if (array.length == 0) {
                    return;
                }
                for (Object o : array) {
                    handleValue(o);
                }
            }else {
                handleValue(result);
            }
        }
    }

    @SneakyThrows
    private void handleValue(Object o){
        Field[] fields = o.getClass().getDeclaredFields();

        for (Field field : fields) {
            if(field.getGenericType().toString().equals("class java.math.BigDecimal")){
                //只处理BigDecimal类型字段
                //这个字段需要赋值
                field.setAccessible(true);
                BigDecimal value = (BigDecimal) field.get(o);

                //String result = value.stripTrailingZeros().toPlainString();
                BigDecimal result = value.stripTrailingZeros();

                field.set(o,result);
            }
        }
    }
}